import {getLyric} from 'api/song'
import {ERR_OK} from 'api/config'
import { Base64 } from 'js-base64'

export default class song {
    constructor({ id, mid, singer, name, album, duration, image, url }) {
        this.id = id
        this.mid = mid
        this.singer = singer
        this.name = name
        this.album = album
        this.duration = duration
        this.image = image
        this.url = url
    }

    // 获取歌词
    getLyric() {
        if (this.lyric) {
            return Promise.resolve(this.lyric)
        }

        return new Promise((resolve, reject) => {
            getLyric(this.mid).then((res) => {
                if ( res.retcode === ERR_OK ) {
                    this.lyric = Base64.decode(res.lyric)
                    resolve(this.lyric)
                } else {
                    reject('no lyric')
                }
            })
        })
    }
}

// 工厂方法
export function createSong(musicData, songVkey) {
    return new song({
        id: musicData.songid,
        mid: musicData.songmid,
        singer: filterSinger(musicData.singer),
        name: musicData.songname,
        album: musicData.albumname,
        duration: musicData.interval,
        image: `https://y.qq.com/music/photo_new/T002R300x300M000${musicData.albummid}.jpg?max_age=2592000`,
        // url: `http://dl.stream.qqmusic.qq.com/C400${musicData.songmid}.m4a?vkey=${songVkey}&guid=7981028948&uin=0&fromtag=66`
        url: `http://dl.stream.qqmusic.qq.com/C40000${musicData.songmid}.m4a?guid=461236210&vkey=6468020A7E064944926E6AF121A062C53F94546463C4AA50A7147B75E30ACA1F6E4974D3FC3CC8ECA236AF36754FAEE8235E4370C314C7F4&uin=0&fromtag=66`
    })
}

// 推荐歌单的歌曲创建函数
export function createRecommendSong(musicData, songVkey) {
    return new song({
        id: musicData.id,
        mid: musicData.mid,
        singer: filterSinger(musicData.singer),
        name: musicData.name,
        album: musicData.album.name,
        duration: musicData.interval,
        image: `https://y.qq.com/music/photo_new/T002R300x300M000${musicData.albummid}.jpg?max_age=2592000`,
        url: `http://dl.stream.qqmusic.qq.com/C400${musicData.songmid}.m4a?vkey=${songVkey}&guid=7981028948&uin=0&fromtag=66`
    })
}

function filterSinger(singer) {
    let ret = []
    if (!singer) {
        return ''
    }
    singer.forEach((res) => {
        ret.push(res.name)
    })
    return ret.join('/')
}